import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const uid = ref(localStorage.getItem('uid') || '')
  
  // 安全地解析用户信息
  let userInfoData = {}
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      userInfoData = JSON.parse(userInfoStr)
    }
  } catch (error) {
    console.error('解析用户信息失败:', error)
    localStorage.removeItem('userInfo') // 清除无效数据
  }
  
  const userInfo = ref(userInfoData)
  
  // 用户角色信息
  let roleData = []
  try {
    const roleStr = localStorage.getItem('userRoles')
    if (roleStr) {
      roleData = JSON.parse(roleStr)
    }
  } catch (error) {
    console.error('解析角色信息失败:', error)
    localStorage.removeItem('userRoles')
  }
  
  const userRoles = ref(roleData)
  const isLoggedIn = computed(() => !!token.value)
  const isSuperAdmin = computed(() => userRoles.value.includes('super_admin'))
  
  // 初始化时检查并修复无效数据
  const initializeStore = () => {
    try {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr && userInfoStr !== 'undefined') {
        userInfoData = JSON.parse(userInfoStr)
        userInfo.value = userInfoData
      } else {
        localStorage.removeItem('userInfo')
      }
    } catch (error) {
      console.error('初始化用户存储失败:', error)
      localStorage.removeItem('userInfo')
    }
  }
  
  // 在创建存储时立即初始化
  initializeStore()

  // 方法
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const setUid = (newUid) => {
    uid.value = newUid
    localStorage.setItem('uid', newUid)
  }

  const setUserInfo = (info) => {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }

  const setUserRoles = (roles) => {
    userRoles.value = roles
    localStorage.setItem('userRoles', JSON.stringify(roles))
  }

  const logout = () => {
    token.value = ''
    uid.value = ''
    userInfo.value = {}
    userRoles.value = []
    localStorage.removeItem('token')
    localStorage.removeItem('uid')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userRoles')
  }

  return {
    token,
    uid,
    userInfo,
    userRoles,
    isLoggedIn,
    isSuperAdmin,
    setToken,
    setUid,
    setUserInfo,
    setUserRoles,
    logout
  }
})